﻿using cuiail.DBModels;
using Dapper;

namespace cuiail.DBConnections
{
    public interface ICurrentWorkModeService
    {
        Task<CurrentWorkingMode2> GetCurrentWorkingModeAsync();
        Task<bool> InsertCurrentWorkingModeAsync(int currentWorkingMode);
    }

    public class CurrentWorkModeService : ICurrentWorkModeService
    {
        private readonly IDbConnectionFactory _connectionFactory;
        public CurrentWorkModeService(IDbConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
        }

        public async Task<CurrentWorkingMode2> GetCurrentWorkingModeAsync()
        {
            using var connection = _connectionFactory.CreateConnection();
            const string sql = @$"SELECT a.CurrentWorkModeID,a.InsertTime,a.WorkingModeId,b.WorkingModeName FROM cuiail.currentworkmode a
left join cuiail.workingmode b on a.WorkingModeId=b.WorkingModeID
order by InsertTime desc limit 1";
            return await connection.QueryFirstAsync<CurrentWorkingMode2>(sql);
        }


        /// <summary>
        /// 向CurrentWorkMode表插入当前工作模式记录
        /// </summary>
        public async Task<bool> InsertCurrentWorkingModeAsync(int currentWorkingMode)
        {
            // 1. 输入参数校验（避免无效数据插入）
            if (currentWorkingMode == null)
                throw new ArgumentNullException(nameof(currentWorkingMode), "插入的工作模式数据不能为空");

            // 2. 定义插入SQL（仅操作CurrentWorkMode表，InsertTime用数据库默认时间或传入值）
            // 说明：CurrentWorkModeID是自增主键，无需手动插入；InsertTime优先用实体传入值，无值则用数据库当前时间
            const string sql = @"
        INSERT INTO cuiail.currentworkmode (WorkingModeId, InsertTime)
        VALUES (@WorkingModeId, @InsertTime);";

            // 3. 构建参数（参数化查询，避免SQL注入）
            var parameters = new DynamicParameters();
            parameters.Add("@WorkingModeId", currentWorkingMode); 
            parameters.Add("@InsertTime", DateTime.Now);

            // 4. 异步执行插入（管理数据库连接，返回受影响行数）
            using var connection = _connectionFactory.CreateConnection();
            int affectedRows = await connection.ExecuteAsync(sql, parameters);

            // 5. 判断插入结果（受影响行数=1表示插入成功）
            return affectedRows > 0;
        }
    }
}
